package mammuthus.client

import com.google.inject.{Singleton, Inject}
import com.webdm.common.tools.StringUtil
import net.csdn.common.settings.Settings
import org.I0Itec.zkclient.{IZkDataListener, ZkClient}
import org.slf4j.LoggerFactory

import java.util

@Singleton
class ZKClientWrapper @Inject()(settings: Settings) {

  val logger = LoggerFactory.getLogger(classOf[ZKClientWrapper])

  var client: ZkClient = null

  def configZkClient(servers: String) {
    if (client == null) {
      client = new ZkClient(servers)
    }
  }

  def ifExist(path: String): Boolean = {
    if (path == null || path.isEmpty) {
      return false
    }
    return client.exists(path)
  }

  def getValue(path: String): String = {
    if (path == null || path.isEmpty) {
      return null
    }
    try {
      return client.readData(path)
    } catch {
      case e: Exception => logger.error(e.toString)
      case _ =>
    }

    ""

  }


  def checkAndAddPath(path: Path): Unit = {
    val name: String = path.getName
    if (("/" == name) || ("\\" == name)) {
      return
    }
    else {
      var p: String = path.getPathString.replaceAll("\\+", "/")
      p = p.replaceAll("/+$", "")
      if (ifExist(p)) {
        return
      }
      else {
        checkAndAddPath(path.getParentPath)
        logger.info("add path {}", p)
        client.createPersistent(p)
      }
    }
  }

  def addEphemeralPath(path: String, value: String): Unit = {

    if (path == null) {
      return
    }
    if (client.exists(path)) {
      client.delete(path)
      logger.info("目录已经存在{}", path)
    }


    checkAndAddPath(new Path(path).getParentPath)

    if (value == null || value.isEmpty) {
      client.createEphemeral(path)
    }
    else {
      client.createEphemeral(path, value)
    }
  }

  def addPath(path: String, value: String) {
    if (path == null) {
      return
    }
    checkAndAddPath(new Path(path).getParentPath)
    if (value == null || value.isEmpty) {
      client.createPersistent(path)
    }
    else {
      client.createPersistent(path, value)
    }
  }

  def updatePath(path: String, value: String) {
    if (path == null || value == null || value.isEmpty) {
      return
    }
    if (ifExist(path)) {
      client.writeData(path, value)
    } else {
      addPath(path, value)
    }

  }


  def listConf(dir: String): util.List[String] = client.getChildren(dir)


  def removePath(path: String): Boolean = client.deleteRecursive(path)


  def addDataChangesListener(path: String, confCallBack: ConfCallBack): Unit = {
    if (confCallBack == null || confCallBack == null) {
      return
    }
    else {

      try {
        client.subscribeDataChanges(path, new IZkDataListener {
          override def handleDataChange(dataPath: String, data: Object): Unit = {
            confCallBack.confChange(dataPath, StringUtil.toString(data))
          }

          override def handleDataDeleted(dataPath: String): Unit = {}

          override def hashCode(): Int = confCallBack.hashCode()

          override def equals(obj: scala.Any): Boolean = {

            obj.hashCode() == confCallBack.hashCode()
          }
        })
      } catch {
        case e: Exception => e.printStackTrace()
      }

    }
  }

  def main(args: Array[String]) {
    val dir: String = "/lock/127.0.0.1"
    if (!ifExist(dir)) {
      System.out.println("create dir")
      if (!ifExist("/lock")) {
        client.createPersistent("/lock")
      }
      client.createEphemeral(dir)
    }
    val path: String = client.createEphemeralSequential(dir, null)
    System.out.println("path " + path)
    import scala.collection.JavaConversions._
    for (l <- client.getChildren(dir)) {
      System.out.println(l)
    }
    Thread.sleep(50000)
    client.close
  }

}
